<template>
  <el-dialog
    :title="isEdit ? '获取经纬度' : ''"
    :visible.sync="centerDialogVisible"
    width="600px"
    center
  >
    <div class="dialog-inner">
      <div class="map-search" v-if="isEdit">
        <el-input placeholder="输入地址" v-model="address"></el-input>
        <lb-button size="mini" type="primary" @click="searchMapAddr"
          >搜 索</lb-button
        >
      </div>
      <div class="flex-center pb-lg" style="height: 20px">
        <div class="flex-y-center" v-if="currentLatLng.lng">
          经度：{{ currentLatLng.lng }}
          <div class="ml-md">纬度：{{ currentLatLng.lat }}</div>
        </div>
      </div>
      <div id="container"></div>
    </div>
    <span slot="footer" class="dialog-footer" v-if="isEdit">
      <el-button @click="centerDialogVisible = false">{{
        $t('action.cancel')
      }}</el-button>
      <el-button type="primary" @click="confirmLatLng">{{
        $t('action.comfirm')
      }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
	TMapAddToLat
} from '../../api/index.js'
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: true
    },
    latLng: {
      type: Object,
      default () {
        return {
          lat: '',
          lng: ''
        }
      }
    },
    address: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      centerDialogVisible: false,
      map: null,
      info: null,
      marker: '',
      currentLatLng: {
        lat: '',
        lng: ''
      }
    }
  },
  methods: {
    initMap () {
      let that = this
      
      // 检查腾讯地图API是否加载
      if (typeof qq === 'undefined' || !qq.maps) {
        console.error('腾讯地图API未加载')
        this.$message.error('地图服务加载失败，请刷新页面重试')
        return
      }
      
      let { lat = '', lng = '' } = this.latLng
      lat = lat || 30.657535
      lng = lng || 104.065783
      
      // 使用内部数据而不是直接修改prop
      this.currentLatLng = { lat, lng }
      
      let center, map
      
      try {
        // 中心坐标
        // eslint-disable-next-line no-undef
        center = new qq.maps.LatLng(lat, lng)
        // eslint-disable-next-line no-undef
        map = new qq.maps.Map(document.getElementById('container'), {
          center: center,
          zoom: 12
        })
        that.map = map
        console.log('地图初始化成功')
      } catch (error) {
        console.error('地图初始化失败:', error)
        this.$message.error('地图初始化失败，请检查网络连接')
        return
      }
      
      // eslint-disable-next-line no-undef
      that.info = new qq.maps.InfoWindow({
        map: map
      })
      that.marker = new qq.maps.Marker({
        // 标记的位置
        // eslint-disable-next-line no-undef
        position: center,
        map
      })
      if (!this.isEdit) return
      // eslint-disable-next-line no-undef
      qq.maps.event.addListener(map, 'click', function (val, el) {
        if (that.marker) {
          that.marker.setMap(null)
        }
        let { lat, lng } = val.latLng
        that.currentLatLng = { lat, lng }
        // eslint-disable-next-line no-undef
        that.marker = new qq.maps.Marker({
          // 标记的位置
          // eslint-disable-next-line no-undef
          position: new qq.maps.LatLng(lat, lng),
          map: map
        })
        // that.info.open()
        // that.info.setContent(`<div style="margin:10px;">
        // <p>纬度：${lat}</p>
        // <p>经度：${lng}</p>
        // </div>`)
        // // eslint-disable-next-line no-undef
        // that.info.setPosition(new qq.maps.LatLng(lat, lng));
      })
    },
    openQQMap () {
      setTimeout(() => {
        this.initMap()
        this.initGeocoder()
        if (!this.address) return
        this.searchMapAddr()
      }, 500)
    },
    /**
     * @method 根据位置搜索坐标
     */
    searchMapAddr () {
      let { address } = this
      if (!address || address.trim() === '') {
        this.$message.warning('请输入要搜索的地址')
        return
      }
      
      console.log('搜索地址:', address)
      // 显示加载状态
      this.$message.info('正在搜索地址...')
      
      let that = this
      TMapAddToLat(address).then(res => {
        console.log('地理编码成功:', res)
        
        if (!res || !res.lat || !res.lng) {
          that.$message.error('地址解析失败，未找到对应坐标')
          return
        }
        
        if (that.marker) { 
          that.marker.setMap(null) 
        }
        
        let { lat, lng } = res
        that.currentLatLng = { lat, lng }
        
        // 更新地图中心点
        // eslint-disable-next-line no-undef
        let newCenter = new qq.maps.LatLng(lat, lng)
        that.map.setCenter(newCenter)
        
        // 创建新标记
        // eslint-disable-next-line no-undef
        that.marker = new qq.maps.Marker({
          map: that.map,
          position: newCenter
        })
        
        // 显示成功提示
        that.$message.success(`地址搜索成功！经度: ${lng}, 纬度: ${lat}`)
      }).catch(error => {
        console.error('地理编码失败:', error)
        // 显示具体的错误信息
        let errorMessage = '地址搜索失败'
        if (error && error.message) {
          errorMessage = error.message
        }
        that.$message.error(errorMessage)
      })
    },
    initGeocoder () {
      // 不再需要地理编码器，使用HTTP API
      console.log('使用HTTP API进行地理编码')
    },
    /**
     * @method 确定经纬度
     */
    confirmLatLng () {
      this.centerDialogVisible = false
      this.$emit('selectedLatLng', this.currentLatLng)
    }
  },
  watch: {
    dialogVisible (newValue, oldValue) {
      if (newValue) {
        this.centerDialogVisible = true
        this.openQQMap()
      }
    },
    centerDialogVisible (val) {
      if (!val) {
        this.$emit('update:dialogVisible', false)
      }
    },
    latLng: {
      handler (newValue) {
        if (newValue && newValue.lat && newValue.lng) {
          this.currentLatLng = { ...newValue }
        }
      },
      immediate: true,
      deep: true
    }
  }
}
</script>

<style lang="scss" scoped>
#container {
  width: 500px;
  height: 400px;
  margin: 0 auto;
}
.dialog-inner {
  .map-search {
    display: flex;
    justify-content: center;
    margin-bottom: 20px;
    .el-input {
      width: 300px;
      margin-right: 10px;
    }
  }
}
</style>
